package com.iwat.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.iwat.constant.Constants;
import com.iwat.service.WeixinService;
import com.iwat.vo.AccessTokenVO;
import com.iwat.vo.WeixinResponseResult;
import com.iwat.vo.WeixinUserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author wangweiqiang
 * @Classname WeixinServiceImpl
 * @Date 2022/3/27 16:27
 * @Description TODO
 */
@Slf4j
@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public AccessTokenVO getAccessToken(String appId, String appSecret) {
        AccessTokenVO accessTokenVO = restTemplate.getForObject(Constants.GET_ACCESS_TOKEN_URL.replace("APPID", appId).replace("APPSECRET", appSecret), AccessTokenVO.class);
        return accessTokenVO;
    }

    @Override
    public void getOpenId(HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");
        String state = request.getParameter("state");

        log.debug("======================================= \n code值：" + code);

        String responseContent = restTemplate.getForObject(Constants.AUTH_GET_ACCESS_TOKEN_AND_OPENID
                .replace("APPID", Constants.APP_ID)
                .replace("SECRET", Constants.APP_SECRET)
                .replace("CODE", code), String.class);
        JSONObject result = JSONUtil.parseObj(responseContent);
        String accessToken = result.getStr("access_token");
        String openid = result.getStr("openid");
        String refreshToken = result.getStr("refresh_token");

        log.debug("======================================= \n access_token值：" + accessToken + "\n  openid值：" + openid);

        String redirectUrl = "http://iwat.free.idcfengye.com/api/weixin/basic/getUserInfo?openid=" + openid + "&access_token=" + accessToken;
        try {
            // 授权之后重定向到指定URL（这里是跳转到获取用户基本信息接口）
            response.sendRedirect(redirectUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public WeixinUserInfoVO getUserInfo(String openId, String accessToken) {
        WeixinUserInfoVO weixinUserInfoVO = null;
        String responseContent = restTemplate.getForObject(Constants.AUTH_GET_USER_INFO
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId), String.class);
        weixinUserInfoVO = JSONUtil.toBean(responseContent, WeixinUserInfoVO.class);
        return weixinUserInfoVO;
    }


    @Override
    public String refreshAccessToken(String appId, String refreshToken) {
        String responseResult = restTemplate.getForObject(Constants.AUTH_REFRESH_ACCESS_TOKEN
                .replace("APPID", appId)
                .replace("REFRESH_TOKEN", refreshToken), String.class);
        JSONObject jsonObject = JSONUtil.parseObj(responseResult);
        return jsonObject.getStr("access_token");
    }

    @Override
    public WeixinResponseResult checkAccessToken(String openId, String accessToken) throws Exception {
        String responseResult = restTemplate.getForObject(Constants.AUTH_CHECK_ACCESS_TOKEN
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId), String.class);
        WeixinResponseResult weixinResponseResult = JSONUtil.toBean(responseResult, WeixinResponseResult.class);
        if (weixinResponseResult.getErrcode() != 0) {
            log.error("授权凭证无效：" + responseResult);
            throw new Exception();
        }
        return weixinResponseResult;
    }
}

